
'''	
	This file is part of Roseena.
	
	Copyright (C) 2008	Mohamed Hazem <mohamed.hazem@student.guc.edu.eg>
	Copyright (C) 2008	Mostafa Hany <mostafa.hany@student.guc.edu.eg>

	
	Roseena is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Roseena is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Roseena.	If not, see <http://www.gnu.org/licenses/>.
'''

# disconnect and destroy the thread.

from PyQt4.QtCore import QThread, QDataStream,QString, QFile, QIODevice, QDir, QByteArray, SIGNAL
from PyQt4.QtNetwork import QTcpSocket, QAbstractSocket

class mainSocketThread(QThread):
	'''
	socketThread class responsible for threading sockets on simultaneous incoming requests.
	'''
	def __init__(self, socketId, parent):
		'''
		Constructor
		'''
		QThread.__init__(self, parent)
		self.socketId = socketId

	def run(self):
		print "run for your life"
		self.socket = QTcpSocket()

		if not self.socket.setSocketDescriptor(self.socketId):
			self.emit(SIGNAL("error(int)"), socket.error())
			return

		self.socket.connect(self.socket, SIGNAL("readyRead()"), self.doRead)
		self.exec_()

	def doRead(self):
		if self.socket.canReadLine():
			request = self.socket.readLine()
			# GET fun.mp3 HTTP/1.0
			parts = request.split(' ')

			if len(parts) == 3:
				filename = parts[1]
				self.sendFile(filename)
			else:
				print "Bad request from MainServer"
				self.socket.write("Bad Request\n")

	def sendFile(self, fileName):
		file = QFile("files/%s" % fileName)
		if file.exists() == False:
			print "file not found from MainServer"
			self.socket.write("File Not Found\n")
			return
		if file.open(QIODevice.ReadOnly) != True:
			print "file not found from MainServer"
			self.socket.write("File Not Found\n")
			return
		contents = file.readAll()
		self.socket.write("HTTP/1.0 200 Document follows\n")
		self.socket.write("Content-Length: %i\n" % file.size())
		self.socket.write(contents)
		self.socket.flush()
		file.close()
